﻿using System.Collections.Generic;
using System.Text;

namespace WeChat.AspNet
{
    /// <summary>
    /// 多图文信息类
    /// </summary>
    public class NewsMsg : ResMsg
    {
        /// <summary>
        /// 多图文消息模版。
        /// </summary>
        public const string ArticleTemplate = @"<xml>
  <ToUserName><![CDATA[{0}]]></ToUserName>
  <FromUserName><![CDATA[{1}]]></FromUserName>
  <CreateTime>{2}</CreateTime>
  <MsgType><![CDATA[{3}]]></MsgType>
  <ArticleCount>{4}</ArticleCount>
  <Articles>
    {5}
  </Articles>
</xml>";

        /// <summary>
        /// 图文中每一条消息的模版。
        /// </summary>
        public const string ItemTemplate = @"<item>
      <Title><![CDATA[{0}]]></Title>
      <Description><![CDATA[{1}]]></Description>
      <PicUrl><![CDATA[{2}]]></PicUrl>
      <Url><![CDATA[{3}]]></Url>
    </item>";

        /// <summary>
        /// 构造函数必须传送发送方与接收方用户名。
        /// </summary>
        /// <param name="fromUserName"></param>
        /// <param name="toUserName"></param>
        public NewsMsg(string fromUserName, string toUserName)
            : base(fromUserName, toUserName)
        {
            Articles = new List<Article>();
        }

        /// <summary>
        /// 图文消息集合(1条或多条)。
        /// </summary>
        public List<Article> Articles { get; set; }

        /// <summary>
        /// 消息类型
        /// </summary>
        public override ResMsgType MsgType
        {
            get { return ResMsgType.News;}
        }

        /// <summary>
        /// 把消息对象转换成微信可识别的xml对象。
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            var i = 0;
            foreach (var art in Articles)
            {
                sb.Append(string.Format(ItemTemplate, art.Title, art.Description, art.PicUrl, art.Url));
                i++;
            }
            var xmlContent = string.Format(ArticleTemplate, ToUserName, FromUserName, CreateTime, MsgType, i, sb);
            return xmlContent;
        }
    }
}